<template>
  <div style="width: 100%; height: 100%">

    <!-- v-on="gridEvents" overflow: hidden -->
    <vxe-grid ref="tableRef" v-bind="gridOptions">
      <template #toolbar_buttons>
        <Button type="primary" @click="handleCreate">新增</Button>
        <ImpExcel @success="excelSuccessFn" dateFormat="YYYY-MM-DD">
          <Button class="m-3" :loading="loading"> 导入Excel </Button>
        </ImpExcel>

        <Button @click="aoaToExcel"> 模版下载 </Button>
      </template>
      <template #action="{ row }">
        <TableAction outside :actions="getActions(row)" />
      </template>


    </vxe-grid>


    <FormModal @register="register" @success="handleSuccess" />

    <Modal v-model:visible="applyViewShow" title="导入信息有误" @ok="applyViewClose">
      <div>
        <p v-for="(item, index) in msgList">{{ item }} </p>
      </div>
    </Modal>

  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '@/components/Table';
import {
  stockProductList, stockProductRemove, importStockProduct
} from '@/api/heng/stock';
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';
import {
  vxeTableColumns,
  vxeTableFormSchema,
} from './role.data';
import { aoaToSheetXlsx, ImpExcel } from '@/components/Excel';

import { Tag, Descriptions, DescriptionsItem } from 'ant-design-vue';
import { reactive, ref, unref, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import FormModal from './FormModal.vue';
import { useMessage } from '@/hooks/web/useMessage';
import { useModal } from '@/components/Modal';
import { Modal, Tooltip, Button, Timeline, TimelineItem, MonthPicker } from 'ant-design-vue';
import { ClockCircleOutlined } from '@ant-design/icons-vue';

defineOptions({ name: 'MouldList' });
const { createMessage } = useMessage();
const userStore = useUserStore();

const [register, { openModal, closeModal }] = useModal();
const orderModal = useModal();
const loading = ref(false);
const visible = ref(false);
const applyViewShow = ref(false);

const totalObj = ref({ salesmanDeptList: [] })
const totalTitle = ref("");
const applyHistoryList = ref([]);

const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },

  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
      // queryAll: async ({ form }) => {
      //   return await demoListApi(form);
      // },
    },
  },
});

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field + 'Like'] = value;
    });
  }
  // console.log("----json:", json);
  // ywApproveList xftList
  return stockProductList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}

const findList = (filterList?: VxeTableDefines.FilterCheckedParams<any>[]) => {
  gridOptions.loading = true;
  // 模拟接口
  let queryJson = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      queryJson[field + 'Like'] = value;
    });
  }

  return new Promise<any[]>((resolve) => {
    let pp = {
      page: { currentPage: 1, pageSize: 20 },
      form: queryJson,
    };

    gridOptions.proxyConfig.ajax.query(pp).then((res) => {
      gridOptions.loading = false;
      let resultObj = {
        result: res.data.list,
        page: {
          total: res.data.totalResult,
        },
      };

      resolve(res);
    });
  });
};





function applyViewOpen() {
  applyViewShow.value = true;
}

function applyViewClose() {
  applyViewShow.value = false;
}







function getActions(record) {
  let arr = [
    {
      // icon: 'clarity:note-edit-line',
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    },
    {
      // icon: 'ant-design:delete-outlined',
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否删除？',
        placement: 'left',
        confirm: handleClose.bind(null, record),
      },
    }
  ];


  return arr;
}

function handleCreate() {
  openModal(true, {
    isUpdate: false,
  });
}

function handleEdit(record: Recordable) {
  openModal(true, {
    record
  });
}



function handleClose(record: Recordable) {
  //console.log(record);

  stockProductRemove(record)
    .then((res) => {
      if (res.code == 200) {
        createMessage.success(res.message);
        tableRef.value.commitProxy('reload');

      } else {
        createMessage.error(res.message);

      }

    })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}




function handleSuccess() {
  tableRef.value.commitProxy('reload');
}


/**
 * 导入excel
 * "费用名称","金额","供应商名称","真实物料编号(逗号隔开)","开始日期","退款条件类型","退款条件数量","经办人"
 */
const arrHeader = [
  {
    key: 'mno',
    value: 'ms物料编号',
  },
  {
    key: 'kuWeiName',
    value: '库位名称',
  },
  {
    key: 'num',
    value: '最大数量',
  }
];
const msgList = ref([]);

function getHeadArr() {
  let arr = [];
  arrHeader.forEach((r) => {
    arr.push(r.value);
  });
  return arr;
}

function changeSubmitArr(results) {
  let data = {
    list: [],
  };
  let list = [];
  results.forEach((r) => {
    let json = {};
    for (let key in r) {
      arrHeader.forEach((e) => {
        if (e.value == key) {
          json[e.key] = r[key];
        }
      });
    }
    data.list.push(json);
  });
  return data;
}

function excelSuccessFn(list) {
  let results = list[0].results;
  // console.log(results);
  //去除第一行文字提示 shift 删除第一行
  // results.shift();
  let data = changeSubmitArr(results);
  // console.log(data);
  //
  // return;
  loading.value = true;
  importStockProduct(data)
    .then((res) => {
      loading.value = false;

      if (res.code == 200) {
        if (res.data && res.data.length > 0) {
          // let msg="";
          // for(let i=0;i<res.data.length;i++){
          //   let row= res.data[i];
          //   msg+=`第${row.index}行 ${row.message}\n`
          // }
          msgList.value = res.data;
          // visible.value = true;
          applyViewOpen();
        } else {
          createMessage.success('导入成功!');
          tableRef.value.commitProxy('reload');
        }
      } else {
        loading.value = false;

        createMessage.error(res.message);
      }
    })
    .catch((err) => {
      loading.value = false;
    });
}
function aoaToExcel() {
  // 保证data顺序与header一致
  // let arrHeader=[ "费用名称","金额","供应商名称","产品名称","备注","开始日期","退款条件类型","退款条件数量","经办人"];
  // aoaToSheetXlsx({
  //   data: [],
  //   header: arrHeader,
  //   filename: '费用导入模版.xlsx',
  // });

  window.open('http://220.161.77.66:10111/app_file/excel/库位产品管理.xls');
}


</script>
<style lang="less">
.isReturn_clazz {
  text-align: center;
  cursor: pointer;
}
</style>
